package com.mxf.miaosha.controller;

import com.mxf.miaosha.VO.GoodsDetailVo;
import com.mxf.miaosha.VO.GoodsVO;
import com.mxf.miaosha.redis.GoodsKey;
import com.mxf.miaosha.redis.MiaoshaUserKey;
import com.mxf.miaosha.result.Result;
import com.mxf.miaosha.service.GoodsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.mxf.miaosha.domain.MiaoshaUser;
import com.mxf.miaosha.redis.RedisService;
import com.mxf.miaosha.service.MiaoshaUserService;
import org.thymeleaf.spring4.context.SpringWebContext;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {

	@Autowired
	MiaoshaUserService userService;
	
	@Autowired
	RedisService redisService;

	@Autowired
	GoodsService goodsService;

	@Autowired
	ApplicationContext applicationContext;

	@Autowired
	ThymeleafViewResolver thymeleafViewResolver;

	/**
	 * 商品列表，页面缓存
	 * @param model
	 * @param miaoshaUser
	 * @return
	 */
    @RequestMapping(value = "/to_list", produces = "text/html")
	@ResponseBody
    public String list(HttpServletRequest request, HttpServletResponse response,
					   Model model, MiaoshaUser miaoshaUser) {
		model.addAttribute("user", miaoshaUser);

//        return "goods_list";
		// 取缓存
		String html = redisService.get(GoodsKey.getGoodsList, "", String.class);
		if(!StringUtils.isEmpty(html)) {
			return html;
		}

		// 手动渲染
		List<GoodsVO> goodsVOS = goodsService.listGoodsVO();
		model.addAttribute("goodsList", goodsVOS);
		SpringWebContext springWebContext = new SpringWebContext(request, response, request.getServletContext(),
				request.getLocale(), model.asMap(), applicationContext);
		html = thymeleafViewResolver.getTemplateEngine().process("goods_list", springWebContext);
		if(!StringUtils.isEmpty(html)) {
			redisService.set(GoodsKey.getGoodsList, "", html);
		}
		return html;
	}

	/**
	 * 商品详情
	 * @param model
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/detail2/{goodsId}", produces = "text/html")
	@ResponseBody
	public String detail2(HttpServletRequest request, HttpServletResponse response,
						 Model model, MiaoshaUser user, @PathVariable("goodsId") long id) {
    	model.addAttribute("user", user);

    	String html = redisService.get(GoodsKey.getGoodsDetail, "" + id, String.class);
    	if(!StringUtils.isEmpty(html)) {
    		return html;
		}

    	GoodsVO goodsVO = goodsService.getGoodsVOByGoodsId(id);

    	long startAt = goodsVO.getStartDate().getTime();
    	long endAt = goodsVO.getEndDate().getTime();
    	long now = System.currentTimeMillis();

    	int miaoshaStatus = 0; // 秒杀状态
		int remainSeconds = 0; // 还差多久进入秒杀

		if(now < startAt) { // 秒杀未开始
			miaoshaStatus = 0;
			remainSeconds = (int)((startAt - now) / 1000);
		}else if(now > endAt) {// 秒杀结束
			miaoshaStatus = 2;
			remainSeconds = -1;
		}else { // 秒杀进行中
			miaoshaStatus = 1;
			remainSeconds = 0;
		}

		model.addAttribute("goods", goodsVO);
		model.addAttribute("miaoshaStatus", miaoshaStatus);
		model.addAttribute("remainSeconds", remainSeconds);

		SpringWebContext springWebContext = new SpringWebContext(request, response, request.getServletContext(),
				request.getLocale(), model.asMap(), applicationContext);
		html = thymeleafViewResolver.getTemplateEngine().process("goods_detail", springWebContext);
		if(!StringUtils.isEmpty(html)) {
			redisService.set(GoodsKey.getGoodsDetail, "" + id, html);
		}

		return html;
	}


	@RequestMapping(value="/detail/{goodsId}")
	@ResponseBody
	public Result<GoodsDetailVo> detail(HttpServletRequest request, HttpServletResponse response, Model model, MiaoshaUser user,
										@PathVariable("goodsId")long goodsId) {
		GoodsVO goods = goodsService.getGoodsVOByGoodsId(goodsId);
		long startAt = goods.getStartDate().getTime();
		long endAt = goods.getEndDate().getTime();
		long now = System.currentTimeMillis();
		int miaoshaStatus = 0;
		int remainSeconds = 0;
		if(now < startAt ) {//秒杀还没开始，倒计时
			miaoshaStatus = 0;
			remainSeconds = (int)((startAt - now )/1000);
		}else  if(now > endAt){//秒杀已经结束
			miaoshaStatus = 2;
			remainSeconds = -1;
		}else {//秒杀进行中
			miaoshaStatus = 1;
			remainSeconds = 0;
		}
		GoodsDetailVo vo = new GoodsDetailVo();
		vo.setGoods(goods);
		vo.setUser(user);
		vo.setRemainSeconds(remainSeconds);
		vo.setMiaoshaStatus(miaoshaStatus);
		return Result.success(vo);
	}
    
}